<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  status: ''
})

// 表单参数
const formData = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 'enabled',
  menuIds: []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 菜单列表
const menuOptions = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // add 或 edit

// 表单引用
const formRef = ref(null)

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  
  try {
    // 这里应该是实际的API调用
    // const response = await axios.get('/api/v1/roles', { params: queryParams })
    
    // 模拟数据
    setTimeout(() => {
      const mockData = []
      for (let i = 0; i < queryParams.pageSize; i++) {
        const index = (queryParams.page - 1) * queryParams.pageSize + i + 1
        if (index <= 20) { // 假设总共有20条数据
          mockData.push({
            id: `role-${index}`,
            name: `角色${index}`,
            code: `ROLE_${index}`,
            description: `这是角色${index}的描述信息`,
            status: index % 4 === 0 ? 'disabled' : 'enabled',
            menuIds: [1, 2, 3, 4].filter(n => n % (index % 3 + 1) === 0),
            createdAt: new Date().toISOString()
          })
        }
      }
      
      tableData.value = mockData
      total.value = 20
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取角色列表失败:', error)
    loading.value = false
  }
}

// 获取菜单列表
const getMenuList = async () => {
  try {
    // 这里应该是实际的API调用
    // const response = await axios.get('/api/v1/menus')
    
    // 模拟数据
    menuOptions.value = [
      { id: 1, name: '仪表盘' },
      { id: 2, name: '系统管理' },
      { id: 3, name: '用户管理' },
      { id: 4, name: '角色管理' },
      { id: 5, name: '菜单管理' },
      { id: 6, name: '个人信息' }
    ]
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.page = 1
  getRoleList()
}

// 处理重置
const handleReset = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 处理分页
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getRoleList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  getRoleList()
}

// 处理添加
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加角色'
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑角色'
  dialogType.value = 'edit'
  
  // 填充表单数据
  Object.assign(formData, row)
  
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里应该是实际的API调用
      // await axios.delete(`/api/v1/roles/${row.id}`)
      
      // 模拟成功
      ElMessage.success('删除成功')
      getRoleList()
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败，请稍后再试')
    }
  }).catch(() => {})
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 添加角色
          // await axios.post('/api/v1/roles', formData)
          ElMessage.success('添加成功')
        } else {
          // 编辑角色
          // await axios.put(`/api/v1/roles/${formData.id}`, formData)
          ElMessage.success('编辑成功')
        }
        
        dialogVisible.value = false
        getRoleList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请稍后再试')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.name = ''
  formData.code = ''
  formData.description = ''
  formData.status = 'enabled'
  formData.menuIds = []
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    enabled: '启用',
    disabled: '禁用'
  }
  return statusMap[status] || status
}

// 格式化菜单
const formatMenus = (menuIds) => {
  if (!menuIds || !menuIds.length) return '-'
  
  return menuIds.map(id => {
    const menu = menuOptions.value.find(item => item.id === id)
    return menu ? menu.name : id
  }).join(', ')
}

onMounted(() => {
  getRoleList()
  getMenuList()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="角色名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="select-status">
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">添加角色</el-button>
        </div>
      </template>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="menuIds" label="拥有菜单">
          <template #default="scope">
            {{ formatMenus(scope.row.menuIds) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'danger'">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input 
            v-model="formData.code" 
            placeholder="请输入角色编码"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="菜单权限" prop="menuIds">
          <el-select
            v-model="formData.menuIds"
            multiple
            placeholder="请选择菜单权限"
            style="width: 100%"
          >
            <el-option
              v-for="item in menuOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.select-status {
  width: 100px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 